<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleDialogClose"
    :close-on-click-modal="false"
    :class="{'mobile-el-dialog':showMobilePage}"
    modal-append-to-body
    lock-scroll
    class="subcribe-common-dialog normal-common-dialog-size">
    <div class="create-info-box">
      <DialogTitle title="退货入库" font-size="16px" style="margin-bottom: 16px">
        <el-tooltip placement="right">
          <div slot="content">如果有残次品请登记数量，残次品并不影响入库数量。</div>
          <tipIcon is-diy/>
        </el-tooltip>
      </DialogTitle>
      <el-form
        ref="stockOperationForm"
        :model="pendingGoodsForm"
        :rules="formRules"
        class="lineHeight32"
        label-width="100px"
        label-position="right">
        <el-row :class="{'mobile-stock-dialog': showMobilePage}" :style="!showMobilePage?'':{maxHeight: maxHeight}" class="response-el-row" type="flex">
          <el-col :span="labelSpan">
            <el-form-item label="订单编号：" style="margin-bottom: 12px">
              <ToolTip :content="pendingGoodsInfo.afterSaleOrderNum" placement="top-start" />
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="成本价(元)：" style="margin-bottom: 12px">
              <PriceColumn :real-val="pendingGoodsInfo.cost" :price="pendingGoodsInfo.cost" placement="top-start" />
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="总成本(元)：">
              <PriceColumn :real-val="pendingGoodsInfo.totalCosts" :price="pendingGoodsInfo.totalCosts" placement="top-start" />
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="入库数量：">
              <ToolTip :content="pendingGoodsInfo.inventoryCount" placement="top-start" />
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="入库时间：" prop="time">
              <el-date-picker
                v-model="pendingGoodsForm.time"
                :picker-options="pickerOptions"
                type="datetime"
                value-format="timestamp"
                placeholder="请选择"
                format="yyyy/MM/dd HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="含次品数量：" prop="defectiveQuantity">
              <el-input
                v-model="pendingGoodsForm.defectiveQuantity"
                placeholder="请输入"
                type="text"
                @input="valToPureNum"/>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="备注：" prop="remark">
              <el-input
                v-model="pendingGoodsForm.remark"
                rows="3"
                placeholder="请输入"
                resize="none"
                name="remark"
                type="textarea"
                maxlength="500"
                class="remark-input"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button :disabled="fetchLoading" class="ok" type="primary" @click="formValidate">确定</el-button>
      <el-button class="cancel-btn-style" type="info" @click="handleDialogClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DialogTitle from '@/components/Title';
import { takeStock } from '@/api/mengli';
import { mapState } from 'vuex';

export default {
  components: {
    DialogTitle
  },
  data() {
    return {
      dialogVisible: false,
      pendingGoodsInfo: {},
      pendingGoodsForm: {
        time: null,
        defectiveQuantity: null,
        remark: ''
      },
      fetchLoading: false,
      maxHeight: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    formRules() {
      return {
        time: [{ required: true, trigger: 'change', message: '请选择入库时间' }]
      };
    },
    pickerOptions() {
      return {
        disabledDate(time) {
          const now = new Date();
          const year = now.getFullYear();
          const month = now.getMonth();
          const deadline = new Date(year, month - 1, 1, 0, 0, 0);
          return time.getTime() < deadline.getTime();
        }
      };
    },
    labelSpan() {
      return this.showMobilePage ? 24 : 12;
    }
  },
  watch: {},
  methods: {
    initDialog(data) {
      this.pendingGoodsInfo = _.cloneDeep(data);
      const clientHeight = window.innerHeight;
      this.maxHeight = ((clientHeight * 3) / 5) + 'px';
      this.dialogVisible = true;
    },
    valToPureNum(val) {
      if (val) {
        val = val.replace(/[^\d]/g, '');
        val = val.replace(/^0[^]+/g, '');
      }
      const { inventoryCount } = this.pendingGoodsInfo;
      let num = null;
      if (inventoryCount || inventoryCount === 0) {
        num = Number(val) > Number(inventoryCount) ? inventoryCount : val;
      }
      this.$set(this.pendingGoodsForm, 'defectiveQuantity', num);
    },
    handleDialogClose() {
      this.dialogVisible = false;
      this.$refs['stockOperationForm'].resetFields();
    },
    formValidate() {
      this.$refs['stockOperationForm'].validate(valid => {
        valid && this.handleConfirm();
      });
    },
    // 提交
    handleConfirm() {
      const params = _.cloneDeep(this.pendingGoodsForm);
      params.id = this.pendingGoodsInfo.id;
      this.fetchLoading = true;
      takeStock(params).then(res => {
        this.fetchLoading = false;
        if (res.code === 200) {
          this.$message.success('操作成功');
          this.handleDialogClose();
          this.$emit('successCallback');
        }
      }).catch(_ => {
        this.fetchLoading = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 240px;
}
::v-deep .el-form-item__label {
  padding-right: 5px !important;
}
.response-el-row {
  & ::v-deep {
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      width: 240px;
    }
    .el-date-editor, .el-form-item__content {
      width: 240px;
    }
    .el-input__icon {
      line-height: 32px;
    }
    .el-form-item {
      margin-bottom: 24px;
    }
    .el-select {
      .el-input {
        .el-select__caret {
          color: #333333;
        }
      }
    }
  }
  &.mobile-stock-dialog {
    @include scrollBar($x: hidden, $y: auto);
    .remark-input {
      width: 190px !important;
    }
    &::v-deep {
      .el-input__inner {
        width: 190px;
      }
      .el-date-editor, .el-form-item__content {
        width: 190px;
      }
    }
  }
}
.icon-info {
  cursor: pointer;
  color: #ccc;
  margin-left: 4px;
  &:hover {
    color: #406EFF !important;
  }
}
.create-info-box {
  margin-bottom: 8px;
  .remark-input {
    width: 240px;
    word-break: break-word;
    ::v-deep .el-textarea__inner {
      line-height: 1.8;
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: center;
  .ok {
    width: 120px;
    font-size: 16px;
    padding: 8px 20px;
  }
  .cancel-btn-style {
    font-size: 14px;
    padding: 8px 20px;
    margin-left: 16px !important;
  }
}
</style>
